/**
 * Copyright (C), 2021-2023, 四信物联网有限公司
 * FileName: SessionMemoryImpl
 * Author:   Chapin
 * Date:     2023/10/13 14:35
 * Description: 会话管理基于内存实现
 * History:
 * <author>          <time>          <version>          <desc>
 * 作者姓名           修改时间           版本号              描述
 */
package com.fourfaith.iot.beidou.session;

import io.netty.channel.Channel;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 〈会话管理基于内存实现〉
 * @author Chapin
 * @create 2023/10/13
 * @since 1.0.0
 */
public class SessionMemoryImpl implements Session {
    /**
     * 设备编码关联channel
     */
    private final Map<String, Channel> deviceCodeChannelMap = new ConcurrentHashMap<>();
    /**
     * channel关联设备编码
     */
    private final Map<Channel, String> channelDeviceCodeMap = new ConcurrentHashMap<>();

    /**
     * channel与属性
     */
    private final Map<Channel, Map<String, Object>> channelAttributesMap = new ConcurrentHashMap<>();


    @Override
    public void bind(Channel channel, String deviceCode) {
        deviceCodeChannelMap.put(deviceCode, channel);
        channelDeviceCodeMap.put(channel, deviceCode);
        channelAttributesMap.put(channel, new ConcurrentHashMap<>());
    }

    @Override
    public void unbind(Channel channel) {
        String deviceCode = channelDeviceCodeMap.remove(channel);
        deviceCodeChannelMap.remove(deviceCode);
        channelAttributesMap.remove(channel);
    }

    @Override
    public Object getAttribute(Channel channel, String name) {
        return channelAttributesMap.get(channel).get(name);
    }

    @Override
    public void setAttribute(Channel channel, String name, Object value) {
        Map<String, Object> map = channelAttributesMap.get(channel);
        map.put(name, value);
        channelAttributesMap.put(channel, map);
    }

    @Override
    public Channel getChannel(String deviceCode) {
        return deviceCodeChannelMap.get(deviceCode);
    }

    @Override
    public Map<Channel, String> getChannelMap() {
        return channelDeviceCodeMap;
    }
}